package com.member.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.shop.domain.SysBizGoods;
import com.member.shop.domain.SysBizGoodsSku;
import com.member.shop.domain.SysBizSeckillGoodsPage;
import com.member.shop.domain.SysBizSeckillPage;
import com.member.shop.mapper.*;
import com.member.shop.service.ISysBizSeckillPageService;
import com.member.shop.vo.SysBizGoodsSkuExport;
import com.member.shop.vo.SysBizSeckillPageExport;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 秒杀页Service业务层处理
 *
 * @author lixinchen
 * @date 2025-04-12
 */
@Service
public class SysBizSeckillPageServiceImpl extends ServiceImpl<SysBizSeckillPageMapper, SysBizSeckillPage> implements ISysBizSeckillPageService {
    @Resource
    private SysBizSeckillPageMapper sysBizSeckillPageMapper;


    @Resource
    private SysBizSeckillGoodsPageMapper sysBizSeckillGoodsPageMapper;

    @Resource
    private SysBizGoodsSkuMapper sysBizGoodsSkuMapper;


    @Resource
    private SysBizGoodsMapper sysBizGoodsMapper;

    @Resource
    private SysBizOrderGoodsMapper sysBizOrderGoodsMapper;

    /**
     * 查询秒杀页
     *
     * @param id 秒杀页主键
     * @return 秒杀页
     */
    @Override
    public SysBizSeckillPage selectSysBizSeckillPageById(Long id) {
        SysBizSeckillPage sysBizSeckillPage = sysBizSeckillPageMapper.selectById(id);

        if (sysBizSeckillPage != null) {
            //顶部商品
            SysBizSeckillGoodsPage sysBizSeckillGoodsPage = sysBizSeckillGoodsPageMapper.selectOne(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                    .eq(SysBizSeckillGoodsPage::getIsTop, 0)
                    .eq(SysBizSeckillGoodsPage::getSeckillId, id)
                    .eq(SysBizSeckillGoodsPage::getTenantId, sysBizSeckillPage.getTenantId()));
            if(sysBizSeckillGoodsPage!=null && StringUtils.isNotEmpty(sysBizSeckillGoodsPage.getGoodsId())){
                String goodsId = sysBizSeckillGoodsPage.getGoodsId();
                List<Long> goodsIdList = Arrays.stream(goodsId.split(",")).map(Long::parseLong).collect(Collectors.toList());
                List<SysBizGoodsSku> sysBizGoodsSkus = sysBizGoodsSkuMapper.selectList(new LambdaQueryWrapper<SysBizGoodsSku>()
                        .in(SysBizGoodsSku::getId, goodsIdList)
                        .last("ORDER BY FIELD(id," + goodsId + ")")
                );
                for (SysBizGoodsSku bizGoodsSkus : sysBizGoodsSkus) {
                    SysBizGoods sysBizGoods = sysBizGoodsMapper.selectById(bizGoodsSkus.getGoodsId());
                    bizGoodsSkus.setStockCount(sysBizGoods.getStock()-sysBizGoods.getFrozenStockCount());
                }
                sysBizSeckillPage.setTopGoodsList(sysBizGoodsSkus);
            }


            //分类商品
            List<SysBizSeckillGoodsPage> sysBizSeckillGoodsPages = sysBizSeckillGoodsPageMapper.selectList(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                    .eq(SysBizSeckillGoodsPage::getIsTop, 1)
                    .eq(SysBizSeckillGoodsPage::getSeckillId, id)
                    .eq(SysBizSeckillGoodsPage::getTenantId, sysBizSeckillPage.getTenantId()));

            if (!CollectionUtils.isEmpty(sysBizSeckillGoodsPages)) {
                for (SysBizSeckillGoodsPage bizSeckillGoodsPage : sysBizSeckillGoodsPages) {
                    if(bizSeckillGoodsPage!=null && StringUtils.isNotEmpty(bizSeckillGoodsPage.getGoodsId())){
                        String goodsId = bizSeckillGoodsPage.getGoodsId();
                        List<Long> goodsIdList = Arrays.stream(goodsId.split(",")).map(Long::parseLong).collect(Collectors.toList());
                        List<SysBizGoodsSku> sysBizGoodsSkus = sysBizGoodsSkuMapper.selectList(new LambdaQueryWrapper<SysBizGoodsSku>()
                                .in(SysBizGoodsSku::getId, goodsIdList)
                                .last("ORDER BY FIELD(id," + goodsId + ")")
                        );
                        for (SysBizGoodsSku bizGoodsSkus : sysBizGoodsSkus) {
                            SysBizGoods sysBizGoods = sysBizGoodsMapper.selectById(bizGoodsSkus.getGoodsId());
                            bizGoodsSkus.setStockCount(sysBizGoods.getStock()-sysBizGoods.getFrozenStockCount());
                        }
                        bizSeckillGoodsPage.setGoodsSkuList(sysBizGoodsSkus);
                    }
                }
            }
            sysBizSeckillPage.setCategorizeGoodsList(sysBizSeckillGoodsPages);
        }

        return sysBizSeckillPage;
    }

    /**
     * 查询秒杀页列表
     *
     * @param queryWrapper 秒杀页
     * @return 秒杀页
     */
    @Override
    public List<SysBizSeckillPage> selectSysBizSeckillPageList(LambdaQueryWrapper<SysBizSeckillPage> queryWrapper) {
        return sysBizSeckillPageMapper.selectList(queryWrapper);
    }

    /**
     * 查询秒杀页列表
     *
     * @param sysBizSeckillPage 秒杀页
     * @return 秒杀页
     */
    @Override
    public List<SysBizSeckillPage> selectSysBizSeckillPageList(SysBizSeckillPage sysBizSeckillPage) {
        return sysBizSeckillPageMapper.selectSysBizSeckillPageList(sysBizSeckillPage);
    }

    /**
     * 新增秒杀页
     *
     * @param sysBizSeckillPage 秒杀页
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSysBizSeckillPage(SysBizSeckillPage sysBizSeckillPage) {
        sysBizSeckillPage.setCreateTime(DateUtils.getNowDate());
        int insert = sysBizSeckillPageMapper.insert(sysBizSeckillPage);
        List<SysBizSeckillGoodsPage> all = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sysBizSeckillPage.getTopGoodsList())) {
            String collect = sysBizSeckillPage.getTopGoodsList().stream().map(SysBizGoodsSku::getId).map(String::valueOf).collect(Collectors.joining(","));
            SysBizSeckillGoodsPage sysBizSeckillGoodsPage = new SysBizSeckillGoodsPage();
            sysBizSeckillGoodsPage.setTenantId(sysBizSeckillPage.getTenantId());
            sysBizSeckillGoodsPage.setSeckillId(sysBizSeckillPage.getId());
            sysBizSeckillGoodsPage.setIsTop(0);
            sysBizSeckillGoodsPage.setGoodsId(collect);
            all.add(sysBizSeckillGoodsPage);

            if (sysBizSeckillPage.getDisplayed()==0){
                sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                        new LambdaUpdateWrapper<SysBizGoodsSku>()
                                .in(SysBizGoodsSku::getId,  sysBizSeckillPage.getTopGoodsList().stream().map(SysBizGoodsSku::getId).collect(Collectors.toList()))
                                .set(SysBizGoodsSku::getTag,1));
            }else {
                if (CollectionUtils.isNotEmpty(sysBizSeckillGoodsPage.getGoodsSkuList())) {
                    sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                            new LambdaUpdateWrapper<SysBizGoodsSku>()
                                    .in(SysBizGoodsSku::getId, sysBizSeckillGoodsPage.getGoodsSkuList().stream()
                                            .map(SysBizGoodsSku::getId)
                                            .filter(Objects::nonNull) // 过滤空值
                                            .collect(Collectors.toList()))
                                    .set(SysBizGoodsSku::getTag, null));
                }
            }

        }

        if (CollectionUtils.isNotEmpty(sysBizSeckillPage.getCategorizeGoodsList())) {
            for (SysBizSeckillGoodsPage sysBizSeckillGoodsPage : sysBizSeckillPage.getCategorizeGoodsList()) {
                String collect = sysBizSeckillGoodsPage.getGoodsSkuList().stream().map(SysBizGoodsSku::getId).map(String::valueOf).collect(Collectors.joining(","));
                SysBizSeckillGoodsPage sysBizSeckillGoodsPage1 = new SysBizSeckillGoodsPage();
                sysBizSeckillGoodsPage1.setTenantId(sysBizSeckillPage.getTenantId());
                sysBizSeckillGoodsPage1.setSeckillId(sysBizSeckillPage.getId());
                sysBizSeckillGoodsPage1.setIsTop(1);
                sysBizSeckillGoodsPage1.setModeleTitle(sysBizSeckillGoodsPage.getModeleTitle());
                sysBizSeckillGoodsPage1.setGoodsId(collect);
                all.add(sysBizSeckillGoodsPage1);

                if (sysBizSeckillPage.getDisplayed()==0) {
                    sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                            new LambdaUpdateWrapper<SysBizGoodsSku>()
                                    .in(SysBizGoodsSku::getId, sysBizSeckillGoodsPage.getGoodsSkuList().stream().map(SysBizGoodsSku::getId).collect(Collectors.toList()))
                                    .set(SysBizGoodsSku::getTag, 1));
                }else {
                    if (CollectionUtils.isNotEmpty(sysBizSeckillGoodsPage.getGoodsSkuList())) {
                        sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                                new LambdaUpdateWrapper<SysBizGoodsSku>()
                                        .in(SysBizGoodsSku::getId, sysBizSeckillGoodsPage.getGoodsSkuList().stream()
                                                .map(SysBizGoodsSku::getId)
                                                .filter(Objects::nonNull) // 过滤空值
                                                .collect(Collectors.toList()))
                                        .set(SysBizGoodsSku::getTag, null));
                    }
                }
            }
        }
        sysBizSeckillGoodsPageMapper.inserBatch(all);
        return insert;
    }

    /**
     * 修改秒杀页
     *
     * @param sysBizSeckillPage 秒杀页
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSysBizSeckillPage(SysBizSeckillPage sysBizSeckillPage) {
        sysBizSeckillPage.setUpdateTime(DateUtils.getNowDate());
        int i = sysBizSeckillPageMapper.updateById(sysBizSeckillPage);

        List<SysBizSeckillGoodsPage> sysBizSeckillGoodsPages = sysBizSeckillGoodsPageMapper.selectList(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                .eq(SysBizSeckillGoodsPage::getSeckillId, sysBizSeckillPage.getId()));
        if (!CollectionUtils.isEmpty(sysBizSeckillGoodsPages)) {
            List<Long> longs = new ArrayList<>();
            for (SysBizSeckillGoodsPage sysBizSeckillGoodsPage : sysBizSeckillGoodsPages) {
                List<Long> collect = Arrays.stream(sysBizSeckillGoodsPage.getGoodsId().split(",")).map(Long::parseLong).collect(Collectors.toList());
                longs.addAll(collect);
            }
            sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                    new LambdaUpdateWrapper<SysBizGoodsSku>()
                            .in(SysBizGoodsSku::getId, longs)
                            .set(SysBizGoodsSku::getTag, null));
        }

        sysBizSeckillGoodsPageMapper.delete(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                .eq(SysBizSeckillGoodsPage::getSeckillId, sysBizSeckillPage.getId()));

        List<SysBizSeckillGoodsPage> all = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(sysBizSeckillPage.getTopGoodsList())) {
            String collect = sysBizSeckillPage.getTopGoodsList().stream().map(SysBizGoodsSku::getId).map(String::valueOf).collect(Collectors.joining(","));
            SysBizSeckillGoodsPage sysBizSeckillGoodsPage = new SysBizSeckillGoodsPage();
            sysBizSeckillGoodsPage.setTenantId(sysBizSeckillPage.getTenantId());
            sysBizSeckillGoodsPage.setSeckillId(sysBizSeckillPage.getId());
            sysBizSeckillGoodsPage.setIsTop(0);
            sysBizSeckillGoodsPage.setGoodsId(collect);
            all.add(sysBizSeckillGoodsPage);

            if (sysBizSeckillPage.getDisplayed()==0){
                sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                        new LambdaUpdateWrapper<SysBizGoodsSku>()
                                .in(SysBizGoodsSku::getId,  sysBizSeckillPage.getTopGoodsList().stream().map(SysBizGoodsSku::getId).collect(Collectors.toList()))
                                .set(SysBizGoodsSku::getTag,1));
            }else {
                if (CollectionUtils.isNotEmpty(sysBizSeckillGoodsPage.getGoodsSkuList())) {
                    sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                            new LambdaUpdateWrapper<SysBizGoodsSku>()
                                    .in(SysBizGoodsSku::getId, sysBizSeckillGoodsPage.getGoodsSkuList().stream()
                                            .map(SysBizGoodsSku::getId)
                                            .filter(Objects::nonNull) // 过滤空值
                                            .collect(Collectors.toList()))
                                    .set(SysBizGoodsSku::getTag, null));
                }
            }
        }

        if (CollectionUtils.isNotEmpty(sysBizSeckillPage.getCategorizeGoodsList())) {
            for (SysBizSeckillGoodsPage sysBizSeckillGoodsPage : sysBizSeckillPage.getCategorizeGoodsList()) {

                String collect = sysBizSeckillGoodsPage.getGoodsSkuList().stream().map(SysBizGoodsSku::getId).map(String::valueOf).collect(Collectors.joining(","));
                SysBizSeckillGoodsPage sysBizSeckillGoodsPage1 = new SysBizSeckillGoodsPage();
                sysBizSeckillGoodsPage1.setTenantId(sysBizSeckillPage.getTenantId());
                sysBizSeckillGoodsPage1.setSeckillId(sysBizSeckillPage.getId());
                sysBizSeckillGoodsPage1.setIsTop(1);
                sysBizSeckillGoodsPage1.setModeleTitle(sysBizSeckillGoodsPage.getModeleTitle());
                sysBizSeckillGoodsPage1.setGoodsId(collect);
                all.add(sysBizSeckillGoodsPage1);

                if (sysBizSeckillPage.getDisplayed()==0) {
                    sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                            new LambdaUpdateWrapper<SysBizGoodsSku>()
                                    .in(SysBizGoodsSku::getId, sysBizSeckillGoodsPage.getGoodsSkuList().stream().map(SysBizGoodsSku::getId).collect(Collectors.toList()))
                                    .set(SysBizGoodsSku::getTag, 1));
                }else {
                    if (CollectionUtils.isNotEmpty(sysBizSeckillGoodsPage.getGoodsSkuList())) {
                        sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                                new LambdaUpdateWrapper<SysBizGoodsSku>()
                                        .in(SysBizGoodsSku::getId, sysBizSeckillGoodsPage.getGoodsSkuList().stream()
                                                .map(SysBizGoodsSku::getId)
                                                .filter(Objects::nonNull) // 过滤空值
                                                .collect(Collectors.toList()))
                                        .set(SysBizGoodsSku::getTag, null));
                    }
                }
            }
        }
        sysBizSeckillGoodsPageMapper.inserBatch(all);
        return i;
    }

    /**
     * 批量删除秒杀页
     *
     * @param ids 需要删除的秒杀页主键
     * @return 结果
     */
    @Override
    public int deleteSysBizSeckillPageByIds(Long[] ids) {
        return sysBizSeckillPageMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除秒杀页信息
     *
     * @param id 秒杀页主键
     * @return 结果
     */
    @Override
    public int deleteSysBizSeckillPageById(Long id) {

        List<SysBizSeckillGoodsPage> sysBizSeckillGoodsPages = sysBizSeckillGoodsPageMapper.selectList(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                .eq(SysBizSeckillGoodsPage::getSeckillId, id));
        if (!CollectionUtils.isEmpty(sysBizSeckillGoodsPages)) {
            List<Long> longs = new ArrayList<>();
            for (SysBizSeckillGoodsPage sysBizSeckillGoodsPage : sysBizSeckillGoodsPages) {
                List<Long> collect = Arrays.stream(sysBizSeckillGoodsPage.getGoodsId().split(",")).map(Long::parseLong).collect(Collectors.toList());
                longs.addAll(collect);
            }
            sysBizGoodsSkuMapper.update(new SysBizGoodsSku(),
                    new LambdaUpdateWrapper<SysBizGoodsSku>().in(SysBizGoodsSku::getId, longs).set(SysBizGoodsSku::getTag, 0));
        }


        return sysBizSeckillPageMapper.deleteById(id);
    }

    @Override
    public List<SysBizSeckillPageExport> export(SysBizSeckillPage sysBizSeckillPage) {
        List<SysBizSeckillPageExport> exportList = sysBizSeckillPageMapper.export(sysBizSeckillPage);
        for (SysBizSeckillPageExport sysBizSeckillPageExport : exportList) {
            String goodsId = sysBizSeckillPageExport.getGoodsId();
            List<Long> goodsIdList = Arrays.stream(goodsId.split(",")).map(Long::parseLong).collect(Collectors.toList());
            List<SysBizGoodsSkuExport> sysBizGoodsSkus = sysBizGoodsSkuMapper.exportList(goodsIdList);



            //查询对应的sku在活动期间卖出的数量
            for (SysBizGoodsSkuExport bizGoodsSkus : sysBizGoodsSkus) {

                Long sales = sysBizOrderGoodsMapper.selectKillCount(bizGoodsSkus.getId(), sysBizSeckillPageExport.getActivityStartTime(), sysBizSeckillPageExport.getActivityEndTime());
                bizGoodsSkus.setSales(sales);

            }
            sysBizSeckillPageExport.setGoodsList(sysBizGoodsSkus);
        }
        return exportList;
    }
}
